<?php

namespace App\Http\Controllers;
use DB;
use Illuminate\Http\Request;
use Hash;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
	
	//后台添加用户
    public function getAdd()
    {
    	return view('admin.user.add');
    }
    //接收表单数据
    public function postInsert(Request $request)
    {
    	// if(empty($request->input('username'))){
    	// 	return back()->with('info','用户名不能为空');
    	// }
    	$this->validate($request, [
	        'username' => 'required|regex:[^\w{6,18}$]',
	        'password' => 'required',
	        'repassword' => 'required|same:password',
	        'email' => 'required|email'
    	],[
    		'username.required'=>'用户名不能为空',
    		'username.regex'=>'帐号为6-18位字母数字下划线',
    		'password.required'=>'密码不能为空',
    		'repassword.same'=>'两次密码必须一致',
    		'repassword.required'=>'确认密码不能为空',
    		'email.required'=>'邮箱不能为空',
    		'email.email'=>'邮箱格式不正确'
    	]);

    	$date=$request->only(['username','password','email']);
    	$date['password']=Hash::make($request->input('password'));
    	$date['token']=str_random(50);
    	$res=DB::table('users')->insert($date);
    	if($res){
    		return redirect('/admin/user/index')->with('success','数据添加成功');
    	}else{
    		return back()->with('error','数据添加失败');
    	}
    	// dd($date);

    }

    public function getIndex(Request $request)
    {
    	// if(empty($request->input('keywords'))){
	    // 	$users=DB::table('users')
	    // 	->paginate($request->input('num',10));
    	// }else{
	    // 	$users=DB::table('users')
	    // 	->where('username','like','%'.$request->input('keywords').'%')
	    // 	->paginate($request->input('num',10));
    	// }
        //读取数据 分页
    	$users=DB::table('users')
    	->where(function($query)use($request){
    		$query->where('username','like','%'.$request->input('keywords').'%');
    	})
		->paginate($request->input('num',10));
    	// dd($users);
    	return view('admin.user.index',['users'=>$users,'request'=>$request->all()]);
    }

    public function getEdit($id)
    {
    	$res=DB::table('users')->where('id',$id)->first();
    	return view('admin.user.edit',['userss'=>$res]);
    	// dd($res);
    }

    //修改用户
    public function postUpdate(Request $request)
    {
    	// dd($request->all());
    	$date=$request->only(['username','email']);
    	$id=$request->input('id');

    	$res=DB::table('users')->where('id',$id)->update($date);
    	if($res){
    		return redirect('/admin/user/index')->with('success','数据修改成功');
    	}else{
    		return back()->with('error','数据修改失败');
    	}
    }

    public function getDelete($id)
    {	
    	$res=DB::table('users')->where('id',$id)->delete();
    	if($res){
    		return redirect('/admin/user/index')->with('success','数据删除成功');
    	}else{
    		return back()->with('error','数据删除失败');
    	}
    }
}
